from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField, MultipleFileField
from wtforms.validators import DataRequired, Length, ValidationError
# 导入文件上传需要
from flask_wtf.file import FileField, FileRequired, FileAllowed

# 全局验证器


def a_range(min=0, max=0):
    def _a_range(form, field):
        if not field.data is None and (field.data < min or field.data > max):
            raise ValidationError('必须在 %d 和 %d 之间' % (min, max))

    return _a_range


class LoginForm(FlaskForm):
    username = StringField(
        '名称', render_kw={'placeholder': '你的账号'}, validators=[DataRequired()])
    password = PasswordField(
        '密码', validators=[DataRequired(), Length(min=8, max=128)])
    remember = BooleanField('记住我')
    submit = SubmitField('登录')


# 自定义验证器, 行内验证器
class PrimeForm(FlaskForm):
    # 使用了全局验证器
    number = IntegerField('整数', validators=[a_range(min=-1, max=10)])
    submit = SubmitField('检查素数')

    def validate_number(form, field):
        print(field.data)
        # if field.data is None:
        #     raise ValidationError('不能为空！')
        if not field.data is None and field.data < 1:
            raise ValidationError('必须是正整数！')


# 单个文件上传
class UploadForm(FlaskForm):
    photo = FileField('上传图片', validators=[
                      FileRequired(message='文件不能为空！'), FileAllowed(['jpg', 'jpeg', 'png', 'gif'], message='文件类型不正确!')])
    submit = SubmitField('上传')


# 多个文件上传
class MultiUploadForm(FlaskForm):
    photo = MultipleFileField('上传图片', validators=[DataRequired()])
    submit = SubmitField()
